package copyengine.ui.component.scrollablePanel.element.list.displayContainerSharePool
{
    import copyengine.infoTree.meta.CESDisplayObjectMeta;
    import copyengine.resource.resProxy.CEResProxy;
    import copyengine.ui.infoTree.InfoTreeBuildFacade;
    import copyengine.ui.infoTree.buildTree.InfoTreeBuildResult;

    import flash.geom.Rectangle;

    import starling.display.DisplayObject;

    public class CEListElementSharePool implements ICEListElementDisplayContainerSharePool
    {
        private var mElementMeta:CESDisplayObjectMeta;
        private var mElementBounds:Rectangle;
        private var mResProxy:CEResProxy;

        private var mBuildResultPoolVector:Vector.<InfoTreeBuildResult>;

        public function CEListElementSharePool(_elementMeta:CESDisplayObjectMeta, _resProxy:CEResProxy) {
            mElementMeta = _elementMeta;
            mResProxy = _resProxy;
            mBuildResultPoolVector = new Vector.<InfoTreeBuildResult>();


            var elementContainerBuildResult:InfoTreeBuildResult = getNewBuildResult();
            var elementMc:DisplayObject = elementContainerBuildResult.rootMc as DisplayObject;
            mElementBounds = elementMc.getBounds(elementMc);

            returnITBuildResult(elementContainerBuildResult);
        }

        public function getContainerBounds():Rectangle {return mElementBounds;}


        public function returnITBuildResult(_buildResult:InfoTreeBuildResult):void {
            //在SharePool Dispose以后又Return了Object
            //这种情况会发生在List进行Dispose时候
            if (_buildResult && mBuildResultPoolVector) {
                (_buildResult.rootMc as DisplayObject).visible = false;
                mBuildResultPoolVector.push(_buildResult);
            }
        }

        public function getFreeITBuildResult():InfoTreeBuildResult {
            if (mBuildResultPoolVector.length > 0) {
                var buildResult:InfoTreeBuildResult = mBuildResultPoolVector.pop();
                (buildResult.rootMc as DisplayObject).visible = true;
                return buildResult;
            } else {
                return getNewBuildResult();
            }
        }

        public function dispose():void {
            for each(var buildResult:InfoTreeBuildResult in mBuildResultPoolVector) {
                (buildResult.rootMc as DisplayObject).dispose();
            }
            mBuildResultPoolVector = null;
        }

        private function getNewBuildResult():InfoTreeBuildResult {return InfoTreeBuildFacade.instance.buildDisplayObject(mElementMeta, mResProxy);}

    }
}
